//
//  SpaceViewController.m
//  GYMWinners
//
//  Created by Logic Solutions on 3/11/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "SpaceViewController.h"
#import "SettingListViewController.h"
#import "PractiseCardViewController.h"
#import "CheckOutHistoryViewController.h"
#import "ChangeCommitViewController.h"

#import "ASIHTTPRequest.h"
#import "ASIFormDataRequest.h"
#import "SBJSON.h"
#import "MBProgressHUD.h"
#import "BaseroutAPI.h"
#import "AppDelegate.h"

@implementation SpaceViewController
@synthesize imageView;
@synthesize commitLabel;
@synthesize leftDaysLabel;
@synthesize spaceTypes;
@synthesize tableView;


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    return self;
}

#pragma mark - View lifecycle

-(void)setting{
    
    SettingListViewController* settingList=[[SettingListViewController alloc]init];
    [self.navigationController pushViewController:settingList animated:YES];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    //1. add setting button
    UIBarButtonItem* settingButtonItem=[[UIBarButtonItem alloc] 
                                       initWithTitle:@"设置" 
                                       style:UIBarButtonItemStyleBordered
                                       target:self 
                                       action:@selector(setting)];
    self.navigationItem.rightBarButtonItem= settingButtonItem;
    
    //2. init tableview
    spaceTypes= [[NSArray alloc] initWithObjects:@"我的体验卡",@"最近出勤纪录", nil];
    tableView = [[UITableView alloc] initWithFrame:CGRectMake(22, 240, 280, 130)];
    tableView.delegate=self;
    tableView.dataSource=self;
    tableView.allowsSelection=YES;
    [tableView reloadData];
    
    [self.view addSubview:tableView];
    
    
    NSMutableDictionary *slist = [[NSMutableDictionary alloc] init];
    [slist setObject:[[BaseroutAPI sharedInstance] zGetVarEx:@"customerid"] forKey:@"cid"];
    [self zSendServer:slist theTitle:@"请稍等" theCommand:@"/space/list"];
}

- (void)viewDidUnload
{
    [self setCommitLabel:nil];
    [self setCommitLabel:nil];
    [self setLeftDaysLabel:nil];
    [super viewDidUnload];
}

- (void)dealloc {
    NSLog(@"dealloc space view");
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}


#pragma mark - tableView delegate

- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [spaceTypes count];
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    return @""; //no header
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSLog(@"didSelectRowAtIndexPath:%d",indexPath.row);
    
    if(indexPath.row==0){
        PractiseCardViewController* cardView=[[PractiseCardViewController alloc] init];
        [self.navigationController pushViewController:cardView animated:YES];
    }else if(indexPath.row==1){
        CheckOutHistoryViewController* history=[[CheckOutHistoryViewController alloc] init];
        [self.navigationController pushViewController:history animated:YES];
    }
}

- (UITableViewCell *)tableView:(UITableView *)tv cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString * showTopBoardCellIdentifier = @"ShowSpaceCell"; 
    UITableViewCell* cell=[tableView dequeueReusableCellWithIdentifier:showTopBoardCellIdentifier];
    if(cell==nil){
        cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:showTopBoardCellIdentifier];        
    }
    cell.textLabel.text=[spaceTypes objectAtIndex:indexPath.row];
    cell.accessoryType=UITableViewCellAccessoryDisclosureIndicator;
    
    return cell;
}

#pragma mark - labek delegate

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    
    UITouch *touch = [touches anyObject];
    NSLog(@"click label tag = %d", touch.view.tag);
    if( touch.view.tag == 10 )
    {
        ChangeCommitViewController* changeCommitViewController=[[ChangeCommitViewController alloc] init];
        [self.navigationController pushViewController:changeCommitViewController animated:YES];
    }
}


#pragma mark - ASIFormDataRequest delegate

- (void)requestFinished:(ASIHTTPRequest *)request
{    
    [MBProgressHUD hideHUDForView:self.view animated:YES];
    
    if (request.responseStatusCode == 200) {
        
        NSString *responseString = [request responseString];
        NSLog(@"responseString=[%@]", responseString);   
        NSDictionary *responseDict = [responseString JSONValue];
        
        NSDictionary *CustProd = [responseDict objectForKey:@"currentCustomerProduct"];
        NSDictionary *ProdCommit = [CustProd objectForKey:@"productCommit"];
        NSDictionary *ProdStake = [CustProd objectForKey:@"productStake"];
        NSNumber *customerProductId = [CustProd objectForKey:@"id"];
        NSNumber *ProdCommitDays = [ProdCommit objectForKey:@"commits"];
        NSNumber *ProdStakeDollars = [ProdStake objectForKey:@"stakes"];
        NSNumber *ProdCommitID = [ProdCommit objectForKey:@"id"];
        NSNumber *ProdStakeID = [ProdStake objectForKey:@"id"];
        NSLog(@"Current Commit id=%d, %d=%d days, %d=$%d", [customerProductId intValue], [ProdCommitID intValue], [ProdCommitDays intValue], [ProdStakeID intValue], [ProdStakeDollars intValue]);
        [[BaseroutAPI sharedInstance] zSetVar:@"currentCommit" theValue:[ProdCommitDays stringValue]];
        [[BaseroutAPI sharedInstance] zSetVar:@"currentStake" theValue:[ProdStakeDollars stringValue]];
        [[BaseroutAPI sharedInstance] zSetVar:@"currentCommitID" theValue:[ProdCommitID stringValue]];
        [[BaseroutAPI sharedInstance] zSetVar:@"currentStakeID" theValue:[ProdStakeID stringValue]];
        [[BaseroutAPI sharedInstance] zSetVar:@"currentCustomerProductId" theValue:[customerProductId stringValue]];
        
        self.commitLabel.text = [NSString stringWithFormat:@"承诺：%d天/周，缺勤罚金%2d元/次", [ProdCommitDays intValue], [ProdStakeDollars intValue]];
        
        CustProd = [responseDict objectForKey:@"futureCustomerProduct"];
        customerProductId = [CustProd objectForKey:@"id"];
        ProdCommit = [CustProd objectForKey:@"productCommit"];
        ProdStake = [CustProd objectForKey:@"productStake"];
        ProdCommitDays = [ProdCommit objectForKey:@"commits"];
        ProdStakeDollars = [ProdStake objectForKey:@"stakes"];
        ProdCommitID = [ProdCommit objectForKey:@"id"];
        ProdStakeID = [ProdStake objectForKey:@"id"];
        NSLog(@"Future Commit id=%d, %d=%d days, %d=$%d", [customerProductId intValue], [ProdCommitID intValue], [ProdCommitDays intValue], [ProdStakeID intValue], [ProdStakeDollars intValue]);
        [[BaseroutAPI sharedInstance] zSetVar:@"futureCommit" theValue:[ProdCommitDays stringValue]];
        [[BaseroutAPI sharedInstance] zSetVar:@"futureStake" theValue:[ProdStakeDollars stringValue]];
        [[BaseroutAPI sharedInstance] zSetVar:@"futureCommitID" theValue:[ProdCommitID stringValue]];
        [[BaseroutAPI sharedInstance] zSetVar:@"futureStakeID" theValue:[ProdStakeID stringValue]];
        [[BaseroutAPI sharedInstance] zSetVar:@"futureCustomerProductId" theValue:[customerProductId stringValue]];
        
        [[BaseroutAPI sharedInstance] zSetVar:@"selectedCommitID" theValue:[ProdCommitID stringValue]];
        [[BaseroutAPI sharedInstance] zSetVar:@"selectedStakeID" theValue:[ProdStakeID stringValue]];

        
        NSLog(@"requestFinished SelectedCommitID=%@, SelectedStakeID=%@", [[BaseroutAPI sharedInstance] zGetVarEx:@"selectedCommitID"], [[BaseroutAPI sharedInstance] zGetVarEx:@"selectedStakeID"]);
        
        NSDictionary *weekStatus = [responseDict objectForKey:@"weekStatus"];
        NSNumber *daysToComplete = [weekStatus objectForKey:@"daysToComplete"];
        
        self.leftDaysLabel.text = [NSString stringWithFormat:@"%d天", [daysToComplete intValue]];
        
    } else {
        NSLog(@"Unexpected error");  
        [[BaseroutAPI sharedInstance] MessageBox:@"提示" Message:@"通讯失败"];
    }
    
}

- (void)requestFailed:(ASIHTTPRequest *)request
{    
    [MBProgressHUD hideHUDForView:self.view animated:YES];
    
    NSError *error = [request error];
    NSLog(@"Error=%@", error.localizedDescription);   
    
    [[BaseroutAPI sharedInstance] MessageBox:@"提示" Message:@"通讯失败"];
}

@end
